package com.emokili.ewa.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.jni.Local;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * @author yuepanpan
 */
public class MessageResourceUtil {
    public static String getMessage(String key){
        return getMessage(key,null,null);
    }

    public static String getMessage(String key, Object[] bindArgs){
        return getMessage(key,null,bindArgs);
    }

    public static String getMessage(String key, String lang){
        return getMessage(key,lang,null);
    }

    public static String getMessage(String key, String lang, Object[] bindArgs){
        if(StringUtils.isBlank(key)){
            return null;
        }
        MessageSource bean = SpringUtil.getBean(MessageSource.class);
        return bean.getMessage(key,bindArgs,generateLocal(lang));
    }

    private static Locale generateLocal(String lang){
        Locale locale = LocaleContextHolder.getLocale();
        if(StringUtils.isNotBlank(lang)){
            String splitString[] = lang.split("_");
            locale = new Locale(splitString[0],splitString[1]);
        }
        return locale;
    }

}
